﻿namespace OneWorks.Web.Extension
{
    using System;
    using System.Web;
    using System.Web.Mvc;
    using Newtonsoft.Json;

    public class CustomJsonResult : ActionResult
    {
        private object _data;

        public object Data
        {
            get { return _data; }
            set { _data = value; }
        }

        private Formatting _format;

        public Formatting Format
        {
            get { return _format; }
            set { _format = value; }
        }

        private JsonSerializerSettings _settings;

        public JsonSerializerSettings Settings
        {
            get { return _settings; }
            set { _settings = value; }
        }

        public CustomJsonResult()
        {
        }

        public CustomJsonResult(object data)
        {
            _data = data;
        }

        public CustomJsonResult(object data, Formatting format)
        {
            _data = data;
            _format = format;
        }

        public CustomJsonResult(object data, Formatting format, JsonSerializerSettings settings)
        {
            _data = data;
            _format = format;
            _settings = settings;
        }

        public override void ExecuteResult(ControllerContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }

            HttpResponseBase response = context.HttpContext.Response;
            response.ContentType = "application/json";
            response.Write(JsonConvert.SerializeObject(_data, _format, _settings));
        }
    }
}
